package com.pf.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.pf.aop.EncryptField;
import com.pf.dto.Address;
import com.pf.dto.UserAddress;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/2/13 20:06
 */
public class Test {
    public static void main(String[] args) throws Exception {
//        Class<User> clazz = User.class;
//        Class<? super User> superclass = clazz.getSuperclass();
//        Field[] fields = superclass.getDeclaredFields();
//        System.out.println(fields.length);

        test();
    }

    public static UserAddress buildUserAddress() {
        Address a1 = Address.builder().addressId("1001").addressName("上海市").build();
        Address a2 = Address.builder().addressId("1002").addressName("西安市").build();
        UserAddress userAddress = UserAddress.builder()
                .account("18221177062")
                .password("Abc12345")
                .secretKey("aaaaaaa")
                .addresses(Lists.newArrayList(a1, a2))
                .build();
        userAddress.setBaseId("1");
        userAddress.setBaseName("baseName");
        return userAddress;
    }

    private static void test() throws Exception {

        UserAddress userAddress = buildUserAddress();
        ObjectMapper objectMapper = new ObjectMapper();
        String str = objectMapper.writeValueAsString(userAddress);
        System.out.println("str=" + str);

        Class<? extends UserAddress> clazz = userAddress.getClass();

        Class<?> superclass = clazz.getSuperclass();
        Field[] superFields = superclass.getDeclaredFields();
        if (superFields != null && superFields.length > 0) {
            for (Field field : superFields) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(EncryptField.class) && String.class.equals(field.getType())) {
                    String value = (String) ReflectionUtils.getField(field, userAddress);
                    System.out.println(field.getName() + "=" + value);
                }
            }
        }

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (ClassUtils.isPrimitiveOrWrapper(field.getType())) {
                System.out.println(">>>>" + field.getName() + ":" + field.getType());
            }
            if (field.isAnnotationPresent(EncryptField.class) && String.class.equals(field.getType())) {
                String value = (String) ReflectionUtils.getField(field, userAddress);
                System.out.println(field.getName() + "=" + value);
            }
        }
    }

}
